package com.ruoyi.business.rescueTask.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;

/**
 * 腾讯地图API
 */
public class TencentMapUtil {
    private static final String TENCENT_MAP_API_URL = "https://apis.map.qq.com/ws/geocoder/v1/";
    private static final String KEY = "2K6BZ-V3AKB-VMVUR-JRPQC-GQBSQ-YZFKZ"; // 替换为自己的密钥

    public static String[] getCoordinates(String position) {
        try {
            String encodedPosition = URLEncoder.encode(position, "UTF-8");
            String urlStr = TENCENT_MAP_API_URL + "?address=" + encodedPosition + "&key=" + KEY;
            URL url = new URL(urlStr);
            System.out.println("请求路径："+url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            JSONObject jsonObject = JSONObject.parseObject(response.toString());

            if (jsonObject.getIntValue("status") == 0) {
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject location = result.getJSONObject("location");
                String lng = location.getString("lng");
                String lat = location.getString("lat");
                return new String[]{lng, lat};
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}